import CryptoJS from 'crypto-js'
import { appId } from '@/config'

/**
 * 加密
 * @param data
 * @param key
 * @param iv
 * @returns {string}
 */
export function encrypt(data, key, iv) {
  if (typeof data === 'object') {
    data = JSON.stringify(data)
  }
  return CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(data), CryptoJS.enc.Utf8.parse(key), {
    iv: CryptoJS.enc.Utf8.parse(iv),
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.ZeroPadding
  }).toString()
}

export function decrypt(message, key, iv, topic) {
  const decrypted = CryptoJS.AES.decrypt(message, CryptoJS.enc.Utf8.parse(key), {
    iv: CryptoJS.enc.Utf8.parse(iv),
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.ZeroPadding
  })
  return decrypted.toString(CryptoJS.enc.Utf8)
}

/**
 * 创建uuid
 * @returns {string}
 */
export function createUuid(len = 32, radix = 16) {
  const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
  const uuid = []
  let i
  radix = radix || chars.length

  if (len) {
    for (i = 0; i < len; i++) uuid[i] = chars[0 | (Math.random() * radix)]
  } else {
    let r
    uuid[8] = uuid[13] = uuid[18] = uuid[23] = ''
    uuid[14] = '4'
    for (i = 0; i < 36; i++) {
      if (!uuid[i]) {
        r = 0 | (Math.random() * 16)
        uuid[i] = chars[i === 19 ? (r & 0x3) | 0x8 : r]
      }
    }
  }
  return uuid.join('')
}

export function getEncrypt(key, iv, hasToken = true) {
  const timestamp = new Date().getTime()
  // 格式 "Key+IV+AccessToken+时间戳+保留 位"
  const userJsonStr = localStorage.getItem('user')
  let token = ''
  if (userJsonStr && hasToken) {
    token = JSON.parse(userJsonStr).token
  } else {
    // console.log("%c不需要token", "color:orange");
  }
  const str = `${key}+${iv}+${token}+${timestamp}+`
  const iframe = document.getElementById('encryptIFrame')
  return new Promise((resolve, reject) => {
    try {
      iframe.contentWindow.OTPEncrypt(appId, str, (res) => {
        resolve(res)
      })
    } catch (err) {
      reject(err)
    }
  })
}
